package com.glb.gilibuy.service.impl;

import com.github.pagehelper.PageInfo;
import com.glb.gilibuy.dao.ProductDao;
import com.glb.gilibuy.dao.UserOrderDao;
import com.glb.gilibuy.dao.UserOrderItemDao;
import com.glb.gilibuy.entity.*;
import com.glb.gilibuy.service.OrderItemService;
import com.glb.gilibuy.service.OrderService;
import com.glb.gilibuy.service.ProductService;
import com.glb.gilibuy.service.UserReceiveAddressService;
import com.glb.gilibuy.util.BeanUtil;
import com.glb.gilibuy.util.MapGenerator;
import com.glb.gilibuy.util.SnowflakeIdUtil;
import com.glb.gilibuy.web.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author: Yingtian qian
 * @Date: 2021/8/6 9:15
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private UserOrderDao userOrderDao;

    @Autowired
    private UserOrderItemDao userOrderItemDao;

    @Autowired
    private ProductDao productDao;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private ProductService productService;

    @Autowired
    private UserReceiveAddressService userReceiveAddressService;

    @Override
    public List<UserOrder> selectOrdersByUserId(String userId) {
        if (!"".equals(userId)) {
            UserOrderExample userOrderExample = new UserOrderExample();
            userOrderExample.setOrderByClause("id desc");
            userOrderExample.or().andUserIdEqualTo(userId).andIsDeletedEqualTo(0);
            List<UserOrder> userOrderList = userOrderDao.selectByExample(userOrderExample);
            return userOrderList;
        }
        return null;
    }

    @Override
    public UserOrder selectOrderByOrderId(String orderId) {
        if (!"".equals(orderId)) {
            UserOrderExample userOrderExample = new UserOrderExample();
            userOrderExample.or().andOrderIdEqualTo(orderId).andIsDeletedEqualTo(0);
            System.out.println(userOrderExample);
            List<UserOrder> userOrderList = userOrderDao.selectByExample(userOrderExample);
            if (userOrderList.isEmpty()) {
                return null;
            }
            return userOrderList.get(0);
        }
        return null;
    }

    @Override
    public Map<String, Object> createOrder(Map<String, Object> cartRes, String addressId, String userId) {
        UserReceiveAddress userReceiveAddress = userReceiveAddressService.selectAddressByAddressId(addressId);
        if (userReceiveAddress == null) {
            return MapGenerator.getRes(501, "不存在该收货地址！");
        }
        if (!userReceiveAddress.getUserId().equals(userId)) {
            return MapGenerator.getRes(502, "无权限使用该收货地址！");
        }
        UserOrder userOrder = new UserOrder();
        userOrder.setUserId(userId);
        userOrder.setReceiveName(userReceiveAddress.getReceiveName());
        userOrder.setReceivePhone(userReceiveAddress.getReceivePhone());
        userOrder.setReceiveProvince(userReceiveAddress.getReceiveProvince());
        userOrder.setReceiveCity(userReceiveAddress.getReceiveCity());
        userOrder.setReceiveRegion(userReceiveAddress.getReceiveRegion());
        userOrder.setReceiveAddressDetail(userReceiveAddress.getReceiveAddressDetail());
        userOrder.setOrderState(0);
        userOrder.setPaymentType(0);
        String orderId = String.valueOf(SnowflakeIdUtil.getSnowflakeId());
        userOrder.setOrderId(orderId);
        Date date = new Date();
        userOrder.setGmtCreate(date);
        userOrder.setIsDeleted(0);

        BigDecimal orderPrice = (BigDecimal) cartRes.get("totalPrice");
        userOrder.setOrderPrice(orderPrice);

        //OrderItem的不变的通用属性
        UserOrderItem userOrderItem = new UserOrderItem();
        userOrderItem.setOrderId(orderId);
        userOrderItem.setGmtCreate(date);
        userOrderItem.setIsDeleted(0);

        ProductDetailVO productDetailVO = (ProductDetailVO) cartRes.get("product");
        if (productDetailVO != null) {
            String productId = productDetailVO.getProductId();
            Integer num = productDetailVO.getProductAmount();

            userOrderItem.setProductId(productId);
            userOrderItem.setOrderItemPrice(orderPrice);
            userOrderItem.setOrderItemAmount(num);
            userOrderItem.setOrderItemId(String.valueOf(SnowflakeIdUtil.getSnowflakeId()));
            if (userOrderItemDao.insertSelective(userOrderItem) <= 0) {
                return MapGenerator.getRes(520, "内部错误！");
            }

            //变更库存和销量
            Map<String, Object> error = upSale(productId, num);
            if (error != null) {
                return error;
            }
        }

        List<CartVO> cartVOList = (List<CartVO>) cartRes.get("cartList");
        if (cartVOList != null) {
            for (CartVO cartVO : cartVOList) {
                String productId = cartVO.getProductId();
                Integer num = cartVO.getAmount();

                userOrderItem.setProductId(productId);
                userOrderItem.setOrderItemPrice(cartVO.getProductTotalPrice());
                userOrderItem.setOrderItemAmount(num);
                userOrderItem.setOrderItemId(String.valueOf(SnowflakeIdUtil.getSnowflakeId()));
                if (userOrderItemDao.insertSelective(userOrderItem) <= 0) {
                    return MapGenerator.getRes(520, "内部错误！");
                }

                //变更库存和销量
                Map<String, Object> error = upSale(productId, num);
                if (error != null) {
                    return error;
                }
            }
        }

        if (userOrderDao.insertSelective(userOrder) > 0) {
            return MapGenerator.getRes(200, "生成订单成功！");
        }
        return MapGenerator.getRes(520, "内部错误！");
    }

    @Override
    public List<UserOrder> selectOrdersByUserIdAndState(String userId, Integer state) {
        if (!"".equals(userId) && state != null) {
            UserOrderExample userOrderExample = new UserOrderExample();
            userOrderExample.setOrderByClause("id desc");
            userOrderExample.or().andUserIdEqualTo(userId).andIsDeletedEqualTo(0).andOrderStateEqualTo(state);
            List<UserOrder> userOrderList = userOrderDao.selectByExample(userOrderExample);
            return userOrderList;
        }
        return null;
    }

    @Override
    public PageInfo findOrdersByUserIdAndState(String userId, Integer state) {
        List<UserOrder> userOrderList = null;
        if (state == 999) {
            userOrderList = selectOrdersByUserId(userId);
        } else {
            userOrderList = selectOrdersByUserIdAndState(userId, state);
        }
        if (userOrderList.isEmpty()) {
            return null;
        }
        PageInfo pageInfo = new PageInfo(userOrderList);
        List<UserOrderVO> userOrderVOList = BeanUtil.copyList(userOrderList, UserOrderVO.class);
        for (UserOrderVO userOrderVO : userOrderVOList) {
            List<UserOrderItem> userOrderItemList = orderItemService.selectItemsByOrderId(userOrderVO.getOrderId());
            List<UserOrderItemVO> userOrderItemVOList = BeanUtil.copyList(userOrderItemList, UserOrderItemVO.class);
            for (UserOrderItemVO userOrderItemVO : userOrderItemVOList) {
                Product product = productService.selectProductByProductId(userOrderItemVO.getProductId());
                SearchedProductVO searchedProductVO = new SearchedProductVO();
                BeanUtil.copyOne(product, searchedProductVO);
                userOrderItemVO.setSearchedProductVO(searchedProductVO);
            }
            userOrderVO.setOrderItemList(userOrderItemVOList);
        }
        pageInfo.setList(userOrderVOList);
        return pageInfo;
    }

    @Override
    public Map<String, Object> cancelOrder(UserOrder userOrder) {
        UserOrder userOrderFromDB = selectOrderByOrderId(userOrder.getOrderId());
        if (userOrderFromDB == null) {
            return MapGenerator.getRes(500, "订单不存在！");
        }
        if (!userOrder.getUserId().equals(userOrderFromDB.getUserId())) {
            return MapGenerator.getRes(501, "无权限取消！");
        }
        if (userOrderFromDB.getOrderState() != 0) {
            return MapGenerator.getRes(502, "订单状态不为待支付，不能取消！");
        }

        List<UserOrderItem> userOrderItemList = orderItemService.selectItemsByOrderId(userOrder.getOrderId());
        for (UserOrderItem userOrderItem : userOrderItemList) {
            Product product = productService.selectProductByProductId(userOrderItem.getProductId());
            //变更库存和销量
            Map<String, Object> error = downSale(product.getProductId(), userOrderItem.getOrderItemAmount());
            if (error != null) {
                return error;
            }
            //不可以删除，应取消后还可以查看
            //userOrderItem.setIsDeleted(1);
            if (userOrderItemDao.updateByPrimaryKeySelective(userOrderItem) <= 0) {
                return MapGenerator.getRes(520, "内部错误！");
            }
        }

        //修改订单状态为“手动关闭”，不删除
        userOrderFromDB.setOrderState(-1);
        if (userOrderDao.updateByPrimaryKeySelective(userOrderFromDB) > 0) {
            return MapGenerator.getRes(200, "取消订单成功！");
        }
        return MapGenerator.getRes(520, "内部错误！");
    }

    @Override
    public Map<String, Object> updateOrder(UserOrder userOrder) {
        UserOrder userOrderFromDB = selectOrderByOrderId(userOrder.getOrderId());
        if (userOrderFromDB == null) {
            return MapGenerator.getRes(500, "订单不存在！");
        }
        //该方法不直接面向外部，无权限验证，无参数校验
        //支付类型不空就改
        if (!StringUtils.isEmpty(userOrder.getPaymentType())) {
            userOrderFromDB.setPaymentType(userOrder.getPaymentType());
        }
        //订单状态不空就改
        if (!StringUtils.isEmpty(userOrder.getOrderState())) {
            userOrderFromDB.setOrderState(userOrder.getOrderState());
        }
        //快递单号不空就改
        if (!StringUtils.isEmpty(userOrder.getTrackingNumber())) {
            userOrderFromDB.setTrackingNumber(userOrder.getTrackingNumber());
        }
        // 用userOrderFromDB更新
        if (userOrderDao.updateByPrimaryKeySelective(userOrderFromDB) > 0) {
            return MapGenerator.getRes(200, "修改订单信息成功！");
        }
        return MapGenerator.getRes(520, "内部错误！");
    }

    @Override
    public Map<String, Object> confirmOrder(UserOrder userOrder) {
        UserOrder userOrderFromDB = selectOrderByOrderId(userOrder.getOrderId());
        if (userOrderFromDB == null) {
            return MapGenerator.getRes(500, "订单不存在！");
        }
        if (!userOrder.getUserId().equals(userOrderFromDB.getUserId())) {
            return MapGenerator.getRes(501, "无权限确认收货！");
        }
        if (userOrderFromDB.getOrderState() != 2) {
            return MapGenerator.getRes(502, "订单状态不为待收货，不能确认收货！");
        }

        userOrderFromDB.setOrderState(3);

        // 用userOrderFromDB更新
        if (userOrderDao.updateByPrimaryKeySelective(userOrderFromDB) > 0) {
            return MapGenerator.getRes(200, "确认收货成功！");
        }
        return MapGenerator.getRes(520, "内部错误！");
    }

    @Override
    public Map<String, Object> getOrder(UserOrder userOrder) {
        UserOrder userOrderFromDB = selectOrderByOrderId(userOrder.getOrderId());
        if (userOrderFromDB == null) {
            return MapGenerator.getRes(500, "订单不存在！");
        }
        if (!userOrder.getUserId().equals(userOrderFromDB.getUserId())) {
            return MapGenerator.getRes(501, "无权限访问！");
        }

        UserOrderVO userOrderVO = new UserOrderVO();
        BeanUtil.copyOne(userOrderFromDB, userOrderVO);

        List<UserOrderItem> userOrderItemList = orderItemService.selectItemsByOrderId(userOrderFromDB.getOrderId());
        List<UserOrderItemVO> userOrderItemVOList = BeanUtil.copyList(userOrderItemList, UserOrderItemVO.class);
        for (UserOrderItemVO userOrderItemVO : userOrderItemVOList) {
            Product product = productService.selectProductByProductId(userOrderItemVO.getProductId());
            SearchedProductVO searchedProductVO = new SearchedProductVO();
            BeanUtil.copyOne(product, searchedProductVO);
            userOrderItemVO.setSearchedProductVO(searchedProductVO);
        }
        userOrderVO.setOrderItemList(userOrderItemVOList);

        return MapGenerator.getResWithData(200, "获得订单详情成功", userOrderVO);
    }

    @Override
    public UserOrder addOrder(UserOrder userOrder) {
        //生成订单编号
        userOrder.setOrderId(String.valueOf(SnowflakeIdUtil.getSnowflakeId()));
        //生成时间
        userOrder.setGmtCreate(new Date());
        //激活
        userOrder.setIsDeleted(0);
        System.out.println(userOrder);
        if (userOrderDao.insertSelective(userOrder) > 0) {
            UserOrderExample example = new UserOrderExample();
            example.or().andOrderIdEqualTo(userOrder.getOrderId()).andIsDeletedEqualTo(0);
            return userOrderDao.selectByExample(example).get(0);
        }
        return null;
    }

    @Override
    public int addTrackingNumberToOrder(String orderId, String trackingNumber) {
        UserOrderExample example = new UserOrderExample();
        example.or().andOrderIdEqualTo(orderId).andIsDeletedEqualTo(0);
        if (userOrderDao.selectByExample(example) != null) {
            //更新物流信息
            UserOrder userOrder = new UserOrder();
            userOrder.setTrackingNumber(trackingNumber);
            if (userOrderDao.updateByExampleSelective(userOrder, example) > 0) {
                return 1;
            }
        }
        return 0;
    }

    //变更库存和销量（增加销量）
    private Map<String, Object> upSale(String productId, Integer num) {
        Product productFromDB = productService.selectProductByProductId(productId);

        Integer newAmount = productFromDB.getProductAmount() - num;
        if (newAmount >= 0) {
            productFromDB.setProductAmount(newAmount);
        } else {
            return MapGenerator.getRes(505, "选择数量超过了实时销量！");
        }

        Integer saleCount = productFromDB.getSaleCount();
        if (saleCount == null) {
            saleCount = 0;
        }

        productFromDB.setSaleCount(saleCount + num);
        if (productDao.updateByPrimaryKeySelective(productFromDB) <= 0) {
            return MapGenerator.getRes(520, "内部错误！");
        }
        return null;
    }

    //变更库存和销量（减少销量）
    private Map<String, Object> downSale(String productId, Integer num) {
        Product productFromDB = productService.selectProductByProductId(productId);

        Integer saleCount = productFromDB.getSaleCount();
        if (saleCount == null) {
            return MapGenerator.getRes(505, "销量为空！");
        }

        Integer newSaleCount = saleCount - num;
        if (newSaleCount >= 0) {
            productFromDB.setSaleCount(newSaleCount);
        } else {
            return MapGenerator.getRes(506, "减少数量超过了实时销量！");
        }

        productFromDB.setProductAmount(productFromDB.getProductAmount() + num);
        if (productDao.updateByPrimaryKeySelective(productFromDB) <= 0) {
            return MapGenerator.getRes(520, "内部错误！");
        }
        return null;
    }

    @Override
    public List<UserOrder> findALLOrder() {
        UserOrderExample example = new UserOrderExample();
        example.or();
        if (userOrderDao.selectByExample(example).isEmpty()) {
            return null;
        }
        List<UserOrder> orders = userOrderDao.selectByExample(example);
        return orders;
    }

}
